/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.service.impl;

import me.zhengjie.domain.Book;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.BookRepository;
import me.zhengjie.service.BookService;
import me.zhengjie.service.dto.BookDto;
import me.zhengjie.service.dto.BookQueryCriteria;
import me.zhengjie.service.mapstruct.BookMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author ...
* @date 2020-11-08
**/
@Service
@RequiredArgsConstructor
public class BookServiceImpl implements BookService {

    private final BookRepository bookRepository;
    private final BookMapper bookMapper;

    @Override
    public Map<String,Object> queryAll(BookQueryCriteria criteria, Pageable pageable){
        Page<Book> page = bookRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(bookMapper::toDto));
    }

    @Override
    public List<BookDto> queryAll(BookQueryCriteria criteria){
        return bookMapper.toDto(bookRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BookDto findById(Integer bookId) {
        Book book = bookRepository.findById(bookId).orElseGet(Book::new);
        ValidationUtil.isNull(book.getBookId(),"Book","bookId",bookId);
        return bookMapper.toDto(book);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BookDto create(Book resources) {
        if(bookRepository.findByIsbn(resources.getIsbn()) != null){
            throw new EntityExistException(Book.class,"ISBN",resources.getIsbn());
        }
        return bookMapper.toDto(bookRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Book resources) {
        Book book = bookRepository.findById(resources.getBookId()).orElseGet(Book::new);
        ValidationUtil.isNull( book.getBookId(),"Book","id",resources.getBookId());
        Book book1 = bookRepository.findByIsbn(resources.getIsbn());
        if(book1 != null && !book1.getBookId().equals(book.getBookId())){
            throw new EntityExistException(Book.class,"ISBN",resources.getIsbn());
        }
        book.copy(resources);
        bookRepository.save(book);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer bookId : ids) {
            bookRepository.deleteById(bookId);
        }
    }

    @Override
    public void download(List<BookDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (BookDto book : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("书名", book.getBookName());
            map.put("图书作者", book.getAuthor());
            map.put("简介", book.getSummary());
            map.put("详情", book.getIntroduction());
            map.put("发布年份", book.getPublisherYear());
            map.put("作者摘要/介绍", book.getAuthorAbstract());
            map.put("isbn", book.getIsbn());
            map.put("图书图片路径", book.getPicturePath());
            map.put("分类号", book.getClassificationSymbol());
            map.put("图书数量", book.getNum());
            map.put("是否启用 1启用 0未启用", book.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}